<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <title>文件管理</title>
    <%@ include file="/commons/global.jsp" %>
    <%@ include file="/commons/basejs.jsp" %>
    <link rel="stylesheet" href="${staticPath}/static/imgView/css/normalize.css">
    <style type="text/css">
        #doc_table li{
            position: relative;
            float: left;
            margin: 0px 0px 20px 20px;
        }
        .file{
            width: 100px;
            text-align: center;
            height: 105px;
        }
    </style>
    <script type="text/javascript" src="${staticPath}/static/imgView/dist/BigPicture.min.js"></script>
    <script type="text/javascript">
        var $this;
        $(function(){
          //  parent.progressClose();
            //flag标志位1-向前 -1向后
            getDocs('',1);
            contextMenu();
        })

        function contextMenu(){
            $('.file').on('contextmenu',function (e) {
                 $this=$(this);
                e.preventDefault();
                $('#menu').menu('show',{
                    left:e.pageX,
                    top:e.pageY
                })
            })
        }



        /**
         * 重命名
         */
        function rename(){
            var type="file";
            if($this.hasClass('dir')){
                type="dir";
            }
            var txt=$this.find('span').attr('title');
            var id=$this.data('id');
            console.log(id);
            $this.find('span').before('<input type="text" id="dom'+id+'" value="'+txt+'" onblur="updateFileName(this,\''+txt+'\',\''+id+'\',\''+type+'\')">');
            $this.find('span').html('');
            getSelectPos("dom"+id);
        }
        /**
         *移动
         */
        function removeTo(){
            var txt=$this.find('span').attr('title');
            var id=$this.data('id');
            var dialog=$('<iframe src="${path}/doc/docSelect?id='+id+'"   frameborder="0" style="border:0;width:100%;height:100%;" id="doc_removeTo"></iframe>').dialog({
                title : '移动至',
                width : '80%',
                height : '80%',
                onClose:function(){
                  $(this).dialog('destroy');
                },
                buttons : [ {
                    text : '确定',
                    handler : function() {
                        var selectDirid=document.getElementById('doc_removeTo').contentWindow.document.getElementById('select').value;
                        var selectDirName=document.getElementById('doc_removeTo').contentWindow.document.getElementById('selectName').value;
                        parent.$.messager.confirm('询问', '确认要移动到【'+ selectDirName+'】？', function(b) {
                            if (b) {
                                $.ajax({
                                    url:'${ctxPath}/doc/updatePid',
                                    data:{id:id,pid:selectDirid},
                                    type:'post',
                                    success:function(result){
                                        progressClose();
                                        if(result.success){
                                            dialog.dialog('close');
                                            //刷新
                                            getDocs($('#prev').val(),1);
                                        }
                                    }
                                })
                            }else{
                                dialog.dialog('close');
                            }
                        });

                    }
                } ]
            })
        }
        /**
         * 删除文件
         */
        function remove(){
            var txt=$this.find('span').attr('title');
            var id=$this.data('id');
            var tip='确认要删除【'+txt+'】？';
            if($this.hasClass('dir')){
                tip='确认要删除【'+txt+'】,删除后会将该文件下所有文件删除？'
            }
            parent.$.messager.confirm('询问', tip, function(b) {
                if (b) {
                    progressLoad();
                    var url='${path }/doc/cancel/'+id;
                    $.post(url, {

                    }, function(result) {
                        if (result.success) {
                           showMsg(result.msg);
                            $this.remove();
                        } else {
                            parent.$.messager.alert('错误', result.msg, 'error');
                        }
                        progressClose();
                    }, 'JSON');
                }
            });
        }
        /**
         * 修改文件名
         */
        function updateFileName(obj,txt,id,type){
            var name=$(obj).val();
            $this.find('span').attr('title',name);
            $this.find('span').html(str2span(name,18));
            updateFileNameAjax(id,name);
            $(obj).remove();
        }

        function updateFileNameAjax(id,name){
            $.ajax({
                url:'${ctxPath}/doc/updateFileName',
                data:{id:id,name:name},
                type:'post',
                success:function(data){
                    refreshDoc();
                }
            })
        }
        /**
         * 返回上一级
         */
        function backDoc(){
            var id=$('#prev').val();
          if(!isNull(id)){
            $.ajax({
                url:'${ctxPath}/doc/get/'+id,
                dataType:'json',
                success:function(data){
                    if(data.success){
                        var pid=data.obj.pid;
                        getDocs(pid,-1);
                    }
                }
            })
          }else{
              getDocs("",-1);
          }
        }

        /**
         * 刷新
         */
        function refreshDoc(){
            var searchKey=$('#keyword').val();
            if(searchKey!=''){
                searchDoc(searchKey);
            }else {
                var pid = $('#prev').val();
                getDocs(pid, 1);
            }
        }

        /**
         * 上传文件
         */
        function uploadDoc(){
            var dialog=$('<div>').dialog({
                title: '上传',
                width: '80%',
                height: '80%',
                href:'${ctxPath}/streamUpload/toUpload3?pid='+$('#prev').val(),
                onClose: function () {
                    $(this).dialog('destroy');
                },
                buttons: [{
                    text: '确定',
                    handler: function () {
                        dialog.dialog('close');
                    }
                }]
            })
        }

        /**
         * 随机生成字符串
         */
        function randomString(len) {
            len = len || 32;
            var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz';    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
            var maxPos = $chars.length;
            var pwd = '';
            for (i = 0; i < len; i++) {
                pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
            }
            return pwd;
        }
        function newDir(){
            var random=guid();
            var id=random;
            var pid=$('#prev').val();
            var path = $('#cur_location').text() + "/新建文件夹";
            if($('#cur_location').text()=="/") {
                path = "/新建文件夹";
            }
            var html="";
            html+='<li class="file" data-id="'+random+'" ondblclick="openDir(\''+id+'\',\''+pid+'\',\''+path+'\')"><img src="${staticPath}/static/img/doc/dir.png" alt="" ><br>'
                +'<input type="text" id="'+random+'" value="新建文件夹" onblur="saveFileName(this,\'dir\',\''+random+'\')"><span title="新建文件夹"></span></li>';
            $('#doc_table').append(html);
            getSelectPos(random);
            contextMenu();
        }
        function newDoc(){
            var random=guid();
            var html="";
            html+='<li class="file" data-id="'+random+'"><img src="${staticPath}/static/img/doc/txt.png" alt="" ><br>'
                +'<input type="text" id="'+random+'" value="新建文件" onblur="saveFileName(this,\'file\',\''+random+'\')"><span title="新建文件"></span></li>';
            $('#doc_table').append(html);
            getSelectPos(random);
            contextMenu();
        }

        /**
         * 获取数据
         */
        function getDocs(pid,flag){
            progressLoad();
                $.ajax({
                    url:'${ctxPath}/doc/findByPid',
                    data:{pid:pid,status:1},
                    type:'post',
                    dataType:'json',
                    success:function(result){
                        progressClose();
                        if(result.success){
                            var data=result.obj;
                            render(data,flag);
                        }
                    }
                })
        }
        function openDir(id,pid,path){
            $.ajax({
                url:'${ctxPath}/doc/get/'+id,
                dataType:'json',
                success:function(data) {
                    if (data.success) {
                        var pid = data.obj.pid;
                        var name=data.obj.name;
                        var cur_location=$('#cur_location').text();
                        if(cur_location=="/"){
                            cur_location=cur_location+name;
                        }else{
                            cur_location=cur_location+"/"+name;
                        }
                        $('#cur_location').html(cur_location);
                        $('#prev').val(id);
                        getDocs(id,1);
                    }
                }
            })

        }
        function render(data,flag) {
            $('#doc_table').html('');
            var html="";
            if(data.length>0){
                if(flag==-1){
                    $('#prev').val(data[0].pid=='null'?"":data[0].pid);
                    var cur_location=$('#cur_location').text();
                    cur_location=cur_location.substr(0,cur_location.lastIndexOf('/'));
                    if(cur_location==""){
                        cur_location="/";
                    }
                    $('#cur_location').text(cur_location);
                }
                for(var i=0;i<data.length;i++){
                    if(data[i].type==1){//文件夹
                             html+='<li class="file dir" data-id="'+data[i].id+'" ondblclick="openDir(\''+data[i].id+'\',\''+data[i].pid+'\',\''+data[i].path+'\')"><img src="${staticPath}/static/img/doc/dir.png" alt="" title="'+data[i].name+'">'
                        +'<br>'
                        +'<span title="'+data[i].name+'">'+str2span(data[i].name,18)+'</span>'
                        +' </li>';
                    }else{//文件
                        if(data[i].fileType=='zip' || data[i].fileType=='htm' || data[i].fileType=='html' || data[i].fileType=='pdf' || data[i].fileType=='mp4' || data[i].fileType=='mp3'
                            || data[i].fileType=='ppt'|| data[i].fileType=='xls' || data[i].fileType=='txt'||data[i].fileType=='xlsx'||data[i].fileType=='doc'||data[i].fileType=='py'
                        ||data[i].fileType=='json'||data[i].fileType=='vue'||data[i].fileType=='sql'||data[i].fileType=='js'||data[i].fileType=='java'||data[i].fileType=='xml'||data[i].fileType=='css'){
                            html+='<li class="file" data-id="'+data[i].id+'" ondblclick="openFile(this,\''+data[i].id+'\',\''+data[i].name+'\',\''+data[i].fileType+'\',\''+data[i].attachId+'\')"><img src="${staticPath}/static/img/doc/'+data[i].fileType+'.png" alt="" title="'+data[i].name+'  '+data[i].size+'  '+datetime2Str(data[i].createTime)+'">'
                                +'<br>'
                                +'<span title="'+data[i].name+'">'+str2span(data[i].name,18)+'</span>'
                                +' </li>';
                        }else if(data[i].fileType=='c' || data[i].fileType=='cpp'){
                            html+='<li class="file" data-id="'+data[i].id+'" ondblclick="openFile(this,\''+data[i].id+'\',\''+data[i].name+'\',\''+data[i].fileType+'\',\''+data[i].attachId+'\')"><img src="${staticPath}/static/img/doc/c.png" alt="" title="'+data[i].name+'  '+data[i].size+'  '+datetime2Str(data[i].createTime)+'">'
                                +'<br>'
                                +'<span title="'+data[i].name+'">'+str2span(data[i].name,18)+'</span>'
                                +' </li>';
                        }else if(data[i].fileType=='rar'){
                            html+='<li class="file" data-id="'+data[i].id+'" ondblclick="openFile(this,\''+data[i].id+'\',\''+data[i].name+'\',\''+data[i].fileType+'\',\''+data[i].attachId+'\')"><img src="${staticPath}/static/img/doc/zip.png" alt="" title="'+data[i].name+'  '+data[i].size+'  '+datetime2Str(data[i].createTime)+'">'
                                +'<br>'
                                +'<span title="'+data[i].name+'">'+str2span(data[i].name,18)+'</span>'
                                +' </li>';
                        }else if(data[i].fileType=='png'||data[i].fileType=='jpg'||data[i].fileType=='jpeg'||data[i].fileType=='gif'||data[i].fileType=='PNG'||data[i].fileType=='JPG'||data[i].fileType=='JPEG'||data[i].fileType=='GIF') {
                            html+='<li class="file" data-id="'+data[i].id+'" ondblclick="openFile(this,\''+data[i].id+'\',\''+data[i].name+'\',\''+data[i].fileType+'\',\''+data[i].attachId+'\')"><img src="${staticPath}/static/img/doc/file.png" alt="" title="'+data[i].name+'  '+data[i].size+'  '+datetime2Str(data[i].createTime)+'">'
                                +'<br>'
                                +'<span title="'+data[i].name+'">'+str2span(data[i].name,18)+'</span>'
                                +' </li>';
                        }else{
                            html+='<li class="file" data-id="'+data[i].id+'" ondblclick="openFile(this,\''+data[i].id+'\',\''+data[i].name+'\',\''+data[i].fileType+'\',\''+data[i].attachId+'\')"><img src="${staticPath}/static/img/doc/file.png" alt="" title="'+data[i].name+'  '+data[i].size+'  '+datetime2Str(data[i].createTime)+'">'
                                +'<br>'
                                +'<span title="'+data[i].name+'">'+str2span(data[i].name,18)+'</span>'
                                +' </li>';
                        }
                    }
                }
            }
            $('#doc_table').append(html);
            contextMenu();
        }

        function openFile(obj,id,name,fileType,attachId){
            if(fileType=='pdf'){
                var op= document.createElement('a');
                $(op).attr('href','${ctxPath}/jsp/pdfjs/web/viewer.html?file=/pdfView/view?name%3d'+attachId);
                $(op).attr('target','_blank');
                $(op).attr('id','A'+id);
                $(op).html(name);
                if(!document.getElementById('A'+id)) document.body.appendChild(op);
                op.click();
            }
            if(fileType=='zip'||fileType=='rar'||fileType=='xls'||fileType=='xlsx'){
                $.messager.alert('提示','不支持'+fileType+'文件格式化查看');
                return;
            }

           if(fileType=='png'||fileType=='jpg'||fileType=='jpeg'||fileType=='gif'||fileType=='PNG'||fileType=='JPG'||fileType=='JPEG'||fileType=='GIF') {
                var op= document.createElement('div');
                $(op).attr('id','image_container');
                $(op).attr('class','container');
                var img=document.createElement('img');
                $(img).attr('src','');
                $(op).append(img);
                if(!document.getElementById('image_container')) document.body.appendChild(op);
                BigPicture({
                    el:document.getElementById('image_container'),
                    imgSrc: '${ctxPath}/upload/readImg?id='+attachId
                })
            }

            if(fileType=='java'||fileType=='js'||fileType=='css'||fileType=='py'||fileType=='c'||fileType=='cpp'||fileType=='vue'||fileType=='sql'||fileType=='groovy'||fileType=='txt'
                ||fileType=='jsp'||fileType=='less'||fileType=='ftl'||fileType=='scss'||fileType=='properties'||fileType=='yml'||fileType=='ymal'||fileType=='json'||fileType=='md'||fileType=='xml'||fileType=='html'){
                var opts = {
                    title : name,
                    border : false,
                    closable : true,
                    fit : true,
                    content:'<iframe src="${ctxPath}/doc/readFile?id='+id+'" frameborder="0" style="border:0;width:100%;height:99.5%;" id="doc_read_file_'+id+'"></iframe>'
                };
                parent.addTab(opts);
            }

        }

        function saveFileName(obj,type,id) {
            var txt=$(obj).val();
            var data;
            var fileName;
            if(type=='file'){
               if(txt.lastIndexOf('.')>-1){
                var fileType=txt.substr(txt.lastIndexOf('.')+1,txt.length);
                 fileName=txt.substr(0,txt.lastIndexOf('.'));
                if(fileType=='zip'||fileType=='rar'){
                    $(obj).closest('li').find('img').attr('src','${ctxPth}/static/img/doc/zip.png')
                    fileName=fileName+"."+fileType;
                }else
                if(fileType=='htm'||fileType=='html'||fileType=='xml'){
                    $(obj).closest('li').find('img').attr('src','${ctxPth}/static/img/doc/htm.png')
                    fileName=fileName+"."+fileType;
                }else
                if(fileType=='mp3'){
                    $(obj).closest('li').find('img').attr('src','${ctxPth}/static/img/doc/mp3.png')
                    fileName=fileName+"."+fileType;
                }else
                if(fileType=='mp4'){
                    $(obj).closest('li').find('img').attr('src','${ctxPth}/static/img/doc/mp4.png')
                    fileName=fileName+"."+fileType;
                }else
                if(fileType=='pdf'){
                    $(obj).closest('li').find('img').attr('src','${ctxPth}/static/img/doc/pdf.png')
                    fileName=fileName+"."+fileType;
                }else
                if(fileType=='ppt'){
                    $(obj).closest('li').find('img').attr('src','${ctxPth}/static/img/doc/ppt.png')
                    fileName=fileName+"."+fileType;
                }else
                if(fileType=='xls'){
                    $(obj).closest('li').find('img').attr('src','${ctxPth}/static/img/doc/xls.png')
                    fileName=fileName+"."+fileType;
                }else
                if(fileType=='java'||fileType=='js'||fileType=='css'||fileType=='py'||fileType=='c'||fileType=='cpp'||fileType=='vue'||fileType=='sql'||fileType=='groovy'
                ||fileType=='jsp'||fileType=='less'||fileType=='ftl'||fileType=='scss'||fileType=='properties'||fileType=='yml'||fileType=='ymal'||fileType=='json'||fileType=='md'){
                    $(obj).closest('li').find('img').attr('src','${ctxPth}/static/img/doc/code.png')
                    fileName=fileName+"."+fileType;
                }else if(fileType=='png'||fileType=='jpg'||fileType=='jpeg'||fileType=='gif'||fileType=='PNG'||fileType=='JPG'||fileType=='JPEG'||fileType=='GIF') {
                    $(obj).closest('li').find('img').attr('src','${ctxPth}/static/img/doc/file.png')
                    fileName=fileName+"."+fileType;
                }else{
                    fileName=fileName+".txt";
                    fileType='txt';
                }
                $(obj).next().attr('title',fileName);
                $(obj).next().html(fileName);
               }else{
                  fileType='txt';
                   $(obj).next().attr('title',txt+".txt");
                   $(obj).next().html(txt+".txt");
                   fileName=txt+".txt";
               }
                var pid=$('#prev').val();
                var path = $('#cur_location').text() + "/" + fileName;
                if($('#cur_location').text()=="/") {
                    path = "/" + fileName;
                }
                data={type:2,name:fileName,status:1,path:path,pid:pid,id:id,size:'0kb',fileType:fileType};
                console.log(data)
                $(obj).next().html(fileName);
                saveFile(data,$(obj).closest('li'));
            }else{
                var pid=$('#prev').val();
                var path = $('#cur_location').text() + "/" + $(obj).val();
                if($('#cur_location').text()=="/") {
                    path = "/" + $(obj).val();
                }
                data={type:1,name:$(obj).val(),status:1,path:path,pid:pid,id:id};
                console.log(data)
                $(obj).next().html($(obj).val());
                saveFile(data,$(obj).closest('li'));
            }
            $(obj).remove();
        }

        function saveFile(data,obj){
            $.ajax({
                url:'${ctxPath}/doc/save',
                type:'post',
                data:data,
                dataType:'json',
                success:function(data){
                    if(!data.success){
                        showMsg("新建文件失败");
                        $(obj).remove();
                    }else{
                        refreshDoc();
                    }
                }
            })
        }
        function saveFileformUpload(data){
            $.ajax({
                url:'${ctxPath}/doc/saveFileformUpload',
                type:'post',
                data:data,
                dataType:'json',
                success:function(data) {
                    if (data.success) {
                        refreshDoc();
                    }
                }
            })
        }



        /**
         * 聚焦到末尾
         * @param obj
         */
        function getSelectPos(obj){
            var esrc = document.getElementById(obj);
            if(esrc==null){
                esrc=event.srcElement;
            }
            if(typeof esrc.createTextRange!=="undefined"){
                var rtextRange =esrc.createTextRange();
                rtextRange.moveStart('character',esrc.value.length);
                rtextRange.collapse(true);
                rtextRange.select();
            }else if(typeof esrc.selectionStart!=="undefined"){
                esrc.selectionStart=esrc.value.length;
                esrc.focus();
            };
        }
        //用于生成uuid
        function S4() {
            return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
        }
        function guid() {
            return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
        }

        function search(obj) {
            var name=$(obj).val();
            searchDoc(name);
        }
        function searchDoc(name){
            $.ajax({
                url:'${ctxPath}/doc/findByNameAndStatus',
                data:{name:name,status:1},
                type:'post',
                dataType:'json',
                success:function(data){
                    if(data.success){
                        var data=data.obj;
                        render(data,-1);
                    }
                }
            })
        }

        /**
         *
         * 查看
         */
        function viewTo(){
            var type="file";
            if($this.hasClass('dir')){
                type="dir";
            }
            var txt=$this.find('span').attr('title');
            var id=$this.data('id');
            $.ajax({
                async:false,
                url:'${ctxPath}/doc/get/'+id,
                type:'post',
                dataType:'json',
                success:function(result){
                    if(result.success){
                        var data=result.obj;
                        if(type=='file') {
                            openFile('', id, txt, data.fileType, data.attachId);
                        }else{
                            openDir(id,data.pid,data.path);
                        }
                    }
                }
            })
        }

        function downloadTo(){
            var name=$this.find('span').attr('title');
            var id=$this.data('id');
            $.ajax({
                url:'${ctxPath}/doc/get/'+id,
                type:'post',
                dataType:'json',
                success:function(result){
                    if(result.success){
                        var data=result.obj;
                        var op= document.createElement('a');
                        $(op).attr('href',basePath+"/doc/download/"+id);
                        $(op).attr('id','D'+id);
                        $(op).html(name);
                        if(!document.getElementById('D'+id)) document.body.appendChild(op);
                        op.click();
                    }
                }
            })
        }


    </script>
</head>
<body>
<div class="easyui-layout" data-options="fit:true,border:false" >
    <div data-options="region:'center',border:false" style="padding: 10px;">

        <div style="border-bottom: 1px solid #eee8d5;padding: 10px;">当前位置:
        <span id="cur_location">/</span>
            <input type="hidden"  id="prev" value="">
        </div>
        <div style="padding: 10px;">
            <button class="easyui-linkbutton"  data-options="iconCls:'fi-arrow-left  icon-grey'" onclick="backDoc()">返回</button>
            <button class="easyui-linkbutton" data-options="iconCls:'fi-loop  icon-grey'" onclick="refreshDoc()">刷新</button>
            <button class="easyui-linkbutton" data-options="iconCls:'fi-upload   icon-grey'" onclick="uploadDoc()">上传</button>
            <button class="easyui-linkbutton" data-options="iconCls:'fi-page-filled   icon-grey'" onclick="newDoc()">新建文件</button>
            <button class="easyui-linkbutton" data-options="iconCls:'fi-folder   icon-grey'" onclick="newDir()">新建文件夹</button>
            <input type="text" id="keyword" class="easyui-text" placeholder="搜索...." onkeyup="search(this)">
        </div>
        <div style="padding: 10px;padding-left:0px;">
            <ul style="list-style: none;" id="doc_table">
            </ul>
        </div>
        <div id="menu" class="easyui-menu" style="width:120px;display:none">
            <div onclick="rename()" data-options="iconCls:'fi-pencil'">重命名</div>
            <div onclick="removeTo()" data-options="iconCls:'fi-marker'">移动到</div>
            <div onclick="downloadTo()" data-options="iconCls:'fi-download'">下载</div>
            <div onclick="viewTo()" data-options="iconCls:'fi-zoom-in'">查看</div>
            <div onclick="remove()" data-options="iconCls:'fi-minus'">删除</div>
        </div>

    </div>
</div>
</body>
</html>